﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MCB.Net.Protocol
{
    public class HttpProtocol : IProtocol
    {
        public HttpRequest Request { get; private set; }

        protected MemoryStream stream;

        protected ASCIIEncoding encoding = new ASCIIEncoding();

        public HttpProtocol(HttpRequest request, byte [] buffer)
        {
            stream = new MemoryStream();
            Request = request;
        }

        public void Write(byte[] buffer)
        {
            
        }

        public byte[] Read(byte[] buffer)
        {
            int bufferLength = 0;
            if (buffer != null && buffer.Length > 0)
            {
                bufferLength = Array.IndexOf(buffer, (byte) 0);
                if (bufferLength == -1)
                    bufferLength = buffer.Length;
            }

            stream.Write(buffer, 0, bufferLength);
            string ddd = encoding.GetString(stream.GetBuffer());

            byte carrigeReturn = (byte)13;
            byte newLine = (byte) 10;

            int index = Array.IndexOf(buffer, carrigeReturn);
            if (index > -1 && index < (buffer.Length - 3))
            {
                if ((buffer[index + 1] == newLine) && (buffer[index + 2] == carrigeReturn) && 
                    (buffer[index + 3] == newLine))
                    Request.Complete = true;
            }
            
            return null;
        }
    }
}